import { Notification } from "element-ui";
import axios from "../../request";

const state = {
  fileList: [],
  // 面包屑名称
  breadNameList: [],
  showFileList: [],
  // 面包屑id
  breadList: [],
  checkFiles: [],
  isRow: true,
  uploadList: []
};

const mutations = {
  // 设置当前目录文件夹
  SET_FILELIST(state, fileList) {
    state.fileList = fileList;

    this.commit("file/SORT_FILES");
  },
  // 进入文件夹
  CLICK_FOLDER(state, file) {
    state.breadNameList.push(file.name);
    state.breadList.push(file.id);

    state.checkFiles = [];
  },
  // 回到首页
  GO_ROOT(state) {
    state.breadList.splice(0);
    state.breadNameList.splice(0);
    state.checkFiles = [];
  },
  // 进入面包屑中的文件夹
  GO_ITEM(state, index) {
    state.breadList = state.breadList.splice(0, index + 1);
    state.breadNameList = state.breadNameList.splice(0, index + 1);
    state.checkFiles = [];
  },
  // 返回面包屑
  BACK(state) {
    state.breadList.splice(state.breadList.length - 1);
    state.breadNameList.splice(state.breadNameList.length - 1);
    state.checkFiles = [];
  },
  // 排序
  SORT_FILES(state, list) {
    let sort = localStorage.getItem("sort_by");
    let sortBy = sort.split("_")[0] || "file";
    let sortWith = (sort.split("_")[1] || "down") === "down" ? -1 : 1;

    let lists = list || state.fileList;

    function sortFile(files) {
      switch (sortBy) {
        case "size":
          files.sort((a, b) => {
            if (a.isFolder !== b.isFolder) {
              return a.isFolder < b.isFolder ? 1 : -1;
            }
            return sortWith * (a.size > b.size ? 1 : -1);
          });
          break;
        case "file":
          files.sort((a, b) => {
            if (a.isFolder !== b.isFolder) {
              return a.isFolder < b.isFolder ? 1 : -1;
            }
            return sortWith * (a.name > b.name ? 1 : -1);
          });
          break;
        default:
          files.sort((a, b) => {
            if (a.isFolder !== b.isFolder) {
              return a.isFolder < b.isFolder ? 1 : -1;
            }
            return (
              sortWith *
              (new Date(a.updatedAt).getTime() -
                new Date(b.updatedAt).getTime())
            );
          });
          break;
      }

      files.forEach(file => {
        if (file.children && file.children.length) {
          sortFile(file.children);
        }
      });
    }

    sortFile(lists);
  },
  // 选中一个文件
  CHECK_ONE_FILE(state, fileId) {
    if (state.checkFiles.includes(fileId)) {
      state.checkFiles = state.checkFiles.filter(e => e !== +fileId);
    } else {
      state.checkFiles.push(+fileId);
    }
  },
  // 取消选中一个文件
  UNCHECK_ONE_FILE(state, fileId) {
    state.checkFiles = state.checkFiles.filter(e => e !== fileId);
  },
  CHECK_FILES(state, fileIds) {
    state.checkFiles = fileIds.map(e => +e);
  },
  ADD_FILE(state, file) {
    console.log(file);

    state.fileList.push(file);

    this.commit("file/SORT_FILES");
  },
  // 选定所有文件
  CHECK_ALL_FILES(state) {
    state.checkFiles.length === state.fileList.length
      ? (state.checkFiles = [])
      : (state.checkFiles = state.fileList.map(e => e.id));
  },
  // 清空 checkfiles
  CLEAR_FILES(state) {
    state.checkFiles = [];
  },
  // 切换展示形式
  TRIGGLER_DISPLAY(state, display) {
    state.isRow = display === "row";

    localStorage.setItem("display", display);
  },
  // 上传文件
  ADD_UPLOAD_LIST(state, file) {
    file.parentName = state.breadNameList.length
      ? state.breadNameList[state.breadNameList.length - 1]
      : "我的文件夹";

    file.parentId = state.breadList.length
      ? state.breadList[state.breadList.length - 1]
      : null;

    if (file.size > 1024 * 1024 * 2) {
      Notification.error({
        title: "错误",
        message: "作者比较穷，只可上传小于2MB的图片"
      });
    } else if (file.type.includes("image")) {
      state.uploadList.unshift(file);
    } else {
      Notification.error({
        title: "错误",
        message: "作者比较懒，目前只支持上传图片格式"
      });
    }
  }
};

const actions = {
  // 设置文件列表
  setFileList({ commit }, fileList) {
    commit("SET_FILELIST", fileList);
  },
  // 点击文件夹名称
  clickFolder({ commit }, file) {
    commit("CLICK_FOLDER", file);
    this.dispatch("file/getFileList");
  },
  // 回到首页
  goRoot({ commit }) {
    commit("GO_ROOT");

    this.dispatch("file/getFileList");
  },
  // 进入面包屑子文件夹
  goItem({ commit }, index) {
    commit("GO_ITEM", index);

    this.dispatch("file/getFileList");
  },
  // 返回
  back({ commit }) {
    commit("BACK");

    this.dispatch("file/getFileList");
  },
  // 在移动复制内新增文件夹
  boxAddFolder({ commit, state }, { folderName, pid }) {
    return new Promise(async (resolve, reject) => {
      let parentId = pid || null;

      if (state.breadList.length && !parentId) {
        parentId = state.breadList[state.breadList.length - 1];
      }

      let folder = await axios.post({
        url: "/file/add-folder",
        data: {
          name: folderName,
          parentId
        }
      });

      this.dispatch("file/getFileList");

      resolve(folder.data);
    });
  },
  // 新增文件夹
  addFolder({ commit, state }, folderName) {
    return new Promise(async (resolve, reject) => {
      let parentId = null;

      if (state.breadList.length) {
        parentId = state.breadList[state.breadList.length - 1];
      }

      let folder = await axios.post({
        url: "/file/add-folder",
        data: {
          name: folderName,
          parentId
        }
      });

      this.dispatch("file/getFileList");

      resolve(folder.data);
    });
  },
  // 删除文件
  deleteFileList({ commit }, idArray) {
    return new Promise(async (resolve, reject) => {
      try {
        await axios.post({
          url: "/file/delete-files",
          data: {
            idArray
          }
        });
        this.dispatch("file/getFileList");

        commit("CLEAR_FILES");

        resolve();
      } catch (error) {
        reject(new Error(error));
      }
    });
  },
  // 获取当前文件夹目录
  getFileList({ commit, state }) {
    return new Promise(async (resolve, reject) => {
      commit("SET_FILELIST", []);
      let parentId = null;
      if (state.breadList.length) {
        parentId = state.breadList[state.breadList.length - 1];
      }

      let res = await axios.post({
        url: "/file/get-file-list",
        data: {
          parentId
        }
      });
      commit("SET_FILELIST", res.data);

      resolve();
    });
  },
  // 重命名文件
  renameFile({ commit }, { id, name }) {
    return new Promise(async (resolve, reject) => {
      try {
        await axios.post({
          url: "file/rename-file",
          data: {
            id,
            name
          }
        });

        this.dispatch("file/getFileList");

        resolve();
      } catch (error) {
        reject(new Error(error));
      }
    });
  },
  // 排序文件
  sortFiles({ commit }) {
    commit("SORT_FILES");
  },
  // 选中一个文件
  checkOneFile({ commit }, fileId) {
    commit("CHECK_ONE_FILE", fileId);
  },
  // 取消选中一个文件
  uncheckOneFile({ commit }, fileId) {
    commit("UNCHECK_ONE_FILE", fileId);
  },
  // 选中多个文件
  checkFiles({ commit }, fileIds) {
    commit("CHECK_FILES", fileIds);
  },
  // 清空选中文件
  clearFiles({ commit }) {
    commit("CLEAR_FILES");
  },
  // 复制文件
  copyFiles({ commit, state }, { toFile, call }) {
    return new Promise(async (resolve, reject) => {
      let res = await axios.post({
        url: "/file/copy-files",
        data: {
          idArray: state.checkFiles,
          parentId: toFile.id
        }
      });

      if (res.code === 0) {
        await this.dispatch("file/getFileList");
        resolve();

        Notification.success({
          title: "成功",
          message: "成功"
        });

        call();
      } else {
        reject();
      }
    });
  },
  // 移动文件
  moveFiles({ commit, state }, { toFile, call }) {
    return new Promise(async (resolve, reject) => {
      let res = await axios.post({
        url: "/file/move-files",
        data: {
          idArray: state.checkFiles,
          parentId: toFile.id
        }
      });

      if (res.code === 0) {
        await this.dispatch("file/getFileList");
        resolve();

        Notification.success({
          title: "成功",
          message: "成功"
        });

        call();
      } else {
        reject();
      }
    });
  },
  trigglerDisplay({ commit }, display) {
    commit("TRIGGLER_DISPLAY", display);
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
